//引入axios
import axios from "axios";
//引入qs
import qs from "qs";

//引入路由跳转
import router from "@/router";

//创建axios
const http = axios.create({
    baseURL: "/api/"
});

//登录拦截
http.interceptors.request.use(req => {
    req.headers.authorization = sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')).token : null
    return req
});

//响应拦截
http.interceptors.response.use(res => {
    //判断是否有token  判断token 是否过期
    if (res.data.msg == "请设置请求头,并携带验证字符串" || res.data.msg == "权限非法") {
        //强制跳转登陆页面
        router.push('/login');
    };

    return res.data
});

//封装get请求方法
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        http.get(url, { params }).then(res => resolve(res)).catch(err => reject(err));
    })
};

//封装post请求方法
export const post = (url, params = {}, isTrue = false) => {
    let data = null;
    //参数序列化
    if (isTrue) {
        data = new FormData();
        for (let k in params) {
            data.append(k, params[k]);
        };
    } else {
        data = qs.stringify(params);
    };
    return new Promise((resolve, reject) => {
        http.post(url, data).then(res => resolve(res)).catch(err => reject(err));
    })
}